package com.ruoyi.mall.app.service.impl;

import com.ruoyi.mall.app.service.DtsSeckillBatchService;
import com.ruoyi.mall.common.domain.DtsAd;
import com.ruoyi.mall.common.domain.DtsSeckillBatch;
import com.ruoyi.mall.common.mapper.DtsSeckillBatchMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class DtsSeckillBathServiceImpl implements DtsSeckillBatchService {

    @Autowired
    private DtsSeckillBatchMapper dtsSeckillBatchMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostConstruct
    public void init() {
        // 初始化时加载数据到缓存
        loadSeckillBatchDataToCache();

        List<DtsSeckillBatch> list = dtsSeckillBatchMapper.selectSeckillTime();
        redisTemplate.opsForValue().set("seckillTime", list);
    }

    // 查询秒杀批次列表
    @Override
    public List<DtsSeckillBatch> selectDtsSeckillBathList(DtsSeckillBatch dtsSeckillBath) {
        return dtsSeckillBatchMapper.selectDtsSeckillBatchList(dtsSeckillBath);
    }

    @Override
    public List<DtsSeckillBatch> selectSeckillandGoods() {
        // 优先从缓存获取数据
        List<DtsSeckillBatch> cachedList = getCachedSeckillBatchList();
        if (cachedList != null) {
            return cachedList;
        }

        // 缓存未命中，从数据库获取
        List<DtsSeckillBatch> dtsSeckillBaths = dtsSeckillBatchMapper.selectSeckillandGoods();
        // 使用 Stream API 按 SeckillBatch 分组并合并商品列表
        Map<String, DtsSeckillBatch> groupedMap = dtsSeckillBaths.stream()
                .collect(Collectors.toMap(
                        DtsSeckillBatch::getSeckillBatch,  // 分组键：SeckillBatch
                        batch -> batch,                    // 分组值：直接使用原对象
                        (existing, incoming) -> {          // 合并函数：处理相同批次的情况
                            // 合并商品列表
                            existing.getDtsGoodsList().addAll(incoming.getDtsGoodsList());
                            // 合并其他字段（根据业务需求选择保留哪个值）
                            existing.setTotal(Math.max(existing.getTotal(), incoming.getTotal()));
                            existing.setRemainingQuantity(Math.max(existing.getRemainingQuantity(), incoming.getRemainingQuantity()));
                            // 其他字段...
                            return existing;
                        }
                ));

        // 将 Map 转换为 List
        List<DtsSeckillBatch> resultList = new ArrayList<>(groupedMap.values());

        // 将结果存入缓存
        saveSeckillBatchListToCache(resultList);

        return resultList;
    }

    @Override
    public List<DtsSeckillBatch> selectSeckillTime() {
        // 从缓存中获取
        List<DtsSeckillBatch> cachedList = (List<DtsSeckillBatch>) redisTemplate.opsForValue().get("seckillTime");
        if (cachedList != null) {
            return cachedList;
        }
        List<DtsSeckillBatch> dtsSeckillBaths = dtsSeckillBatchMapper.selectSeckillTime();
        if (dtsSeckillBaths != null) {
            redisTemplate.opsForValue().set("seckillTime", dtsSeckillBaths);
        }
        return dtsSeckillBatchMapper.selectSeckillTime();
    }

    /**
     * 从缓存获取秒杀批次列表
     */
    @SuppressWarnings("unchecked")
    private List<DtsSeckillBatch> getCachedSeckillBatchList() {
        try {
            return (List<DtsSeckillBatch>) redisTemplate.opsForValue().get("seckillBatchList");
        } catch (Exception e) {
            // 记录日志
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 将秒杀批次列表存入缓存
     */
    private void saveSeckillBatchListToCache(List<DtsSeckillBatch> list) {
        try {
            redisTemplate.opsForValue().set("seckillBatchList", list);
        } catch (Exception e) {
            // 记录日志
            e.printStackTrace();
        }
    }

    /**
     * 加载秒杀批次数据到缓存
     */
    private void loadSeckillBatchDataToCache() {
        List<DtsSeckillBatch> dtsSeckillBaths = dtsSeckillBatchMapper.selectSeckillandGoods();
        // 使用 Stream API 按 SeckillBatch 分组并合并商品列表
        Map<String, DtsSeckillBatch> groupedMap = dtsSeckillBaths.stream()
                .collect(Collectors.toMap(
                        DtsSeckillBatch::getSeckillBatch,
                        batch -> batch,
                        (existing, incoming) -> {
                            existing.getDtsGoodsList().addAll(incoming.getDtsGoodsList());
                            existing.setTotal(Math.max(existing.getTotal(), incoming.getTotal()));
                            existing.setRemainingQuantity(Math.max(existing.getRemainingQuantity(), incoming.getRemainingQuantity()));
                            return existing;
                        }
                ));

        List<DtsSeckillBatch> resultList = new ArrayList<>(groupedMap.values());
        saveSeckillBatchListToCache(resultList);
    }
}
